package de.tto.dating.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.thoughtworks.xstream.XStream;

import de.tto.dating.entities.User;
import de.tto.dating.entities.UserDAO;
import de.tto.dating.xml.StatusXML;

public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6588784380697642406L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String email = req.getParameter("email");
		String passowrd = req.getParameter("password");
		StatusXML status = new StatusXML();
		boolean valid = true;

		if (email == null || email.isEmpty()) {
			status.setEmail("Email ist nicht eingegeben");
			valid = false;
		}
		if (passowrd == null || passowrd.isEmpty()) {
			status.setEmail("Passowrd ist nicht eingegeben");
			valid = false;
		}

		PrintWriter out = resp.getWriter();

		if (!valid) {
			out.println(new XStream().toXML(status));
			return;
		}

		User user = new UserDAO().findUserByProperty(User.EMAIL, email);
		if (user == null) {
			status.setEmail("Email nicht gefunden");
			out.println(new XStream().toXML(status));
			return;
		}

		if (!user.getPassword().equals(passowrd)) {
			status.setPassword("Password ist falsch");
			out.println(new XStream().toXML(status));
			return;
		}

		HttpSession session = req.getSession();
		session.setAttribute("login", true);
		session.setAttribute("currentUser", user);

		// resp.sendRedirect(req.getContextPath() + "/home.jsp");

		status.setMain("OK");
		out.println(new XStream().toXML(status));

	}
}
